package karaoke.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import karaoke.excepcion.DAOExcepcion;
import karaoke.modelo.Comprobante;
import java.text.SimpleDateFormat;
import java.util.Date;
import karaoke.util.ConexionBD;

public class ComprobanteDao extends BaseDAO {

	@SuppressWarnings("deprecation")
	public Comprobante insertar(Comprobante vo) throws DAOExcepcion {
		String query = "insert into comprobante (fecha,tipo,mtotal,reserva_idreserva) values (?,?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			java.util.Date utilDate = new java.util.Date();
			java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
            
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setDate(1, sqlDate); 
			stmt.setString(2, vo.getTipo());
			stmt.setDouble(3, vo.getmTotal());
			stmt.setInt(4, (vo.getReserva()).getIdreserva());
						
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
			// Obtener el ultimo id
			int id = 0;
			query = "select last_insert_id()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			vo.setIdcomprobante(id);

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}
	
}
